<template>
  <div class="loginBody">
    <div class="loginDiv">
      <div class="login-content">
        <h1 class="login-title">用户登录</h1>
        <el-form :model="loginForm" label-width="100px"
                 :rules="rules" ref="loginForm">
          <el-form-item label="账号" prop="no">
            <el-input style="width: 200px" type="text" v-model="loginForm.stuNum"
                      autocomplete="off" size="small"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input style="width: 200px" type="password" v-model="loginForm.password"
                      show-password autocomplete="off" size="small" @keyup.enter.native="confirm"></el-input>
          </el-form-item>
          <div class="b"><span @click="forgotPwd">忘记密码？</span></div><br/>
          <el-form-item>

            <el-button style="margin-left: 25px" type="primary" @click="confirm" :disabled="confirm_disabled">确 定</el-button>
            <el-button type="primary" @click="reg()" >注册</el-button>

          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 找回密码 -->
    <el-dialog class="forgotPWD-form"  v-model="dialogPWD" title="找回密码">
      <el-form :model="registerForm" :rules="rules" ref="registerForm" label-width="70px">
        <el-form-item label="学号" prop="stuNum">
          <el-input prefix-icon="el-icon-message" placeholder="学号" maxlength="32"
                    v-model="registerForm.stuNum"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="stuEmail">
          <el-input prefix-icon="el-icon-message" placeholder="请填写邮箱" maxlength="32"
                    v-model="registerForm.stuEmail"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="forPWD">
          <el-input prefix-icon="el-icon-lock" placeholder="请填写 6-18 位密码" type="password" maxlength="18"
                    v-model="registerForm.forPWD" show-password></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="passwordConfirm">
          <el-input prefix-icon="el-icon-lock" placeholder="请填写 6-18 位密码" type="password" maxlength="18"
                    v-model="registerForm.passwordConfirm" show-password></el-input>
        </el-form-item>



        <el-form-item label="验证码" prop="code">
          <el-input  prefix-icon="el-icon-key" placeholder="请填写6位数字验证码" type="number" style="width: 190px"
                     v-model="registerForm.code">
          </el-input>
          <el-button style="margin-left:90px" type="primary" slot="append" @click="sendEmailCode" :disabled="disabled">{{ msg }}</el-button>

        </el-form-item>

        <el-form-item class="btn-r" label-width="0px">
          <el-button type="success"  :loading="loading" @click="submitForm">找回密码</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {useLoginStateStore} from '../store/storeLoginState.js';
import {ElNotification} from "element-plus";
export default {
  name: "login",
  setup(){
    const loginStateStore =  useLoginStateStore();

    return {
      loginStateStore:loginStateStore
    }
  },
  data(){
    var stuEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入邮箱！'))
      } else if (!/^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/.test(value)) {
        return callback(new Error('请输入正确的邮箱！'))
      } else {
        return callback()
      }
    };
    //忘记密码
    var forPWD = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入密码！'))
      } else if (!/(?=.*[a-zA-Z])[a-zA-Z0-9]{6,18}/.test(value)) {
        return callback(new Error("密码长度在6-18个字符，只能包含数字、大小写字母 且 至少包含一个字母！"))
      } else if (this.registerForm.passwordConfirm !== '') {
        this.$refs.registerForm.validateField('passwordConfirm');
        return callback()
      } else {
        return callback()
      }
    };
    var passwordConfirm = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入确认密码！'))
      } else if (!/(?=.*[a-zA-Z])[a-zA-Z0-9]{6,18}/.test(value)) {
        return callback(new Error("密码长度在6-18个字符，只能包含数字、大小写字母 且 至少包含一个字母！"))
      } else if (value !== this.registerForm.password) {
        return callback(new Error('两次输入的密码不一致！'))
      } else {
        return callback()
      }
    };
    var code = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入6位验证码！'))
      } else if (value.length !== 6) {
        return callback(new Error('请输入6位验证码！'))
      } else {
        return callback()
      }
    };
    return{
      confirm_disabled:false,
      dialogPWD:false,
      msg: '点击获取验证码',
      disabled: false,
      // 按钮加载
      loading: false,
      registerForm: {

        stuNum: '',
        roleId: '',
        stuEmail: '',
        forPWD: '',
        passwordConfirm: '',
        code: '',

      },

      loginForm:{
        stuNum:'',
        password:''
      },
      rules:{
        stuNum: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输密码', trigger: 'blur' }
        ],
        stuEmail: [
          {validator: stuEmail, trigger: 'blur'}
        ],
        forPWD: [
          {validator: forPWD, trigger: 'blur'}
        ],
        passwordConfirm: [
          {validator: passwordConfirm, trigger: 'blur'}
        ],
        code: [
          {validator: code, trigger: 'blur'}
        ]

      }
    }
  },
  methods:{
    confirm() {
      let _this = this;
      //用ajax请求获得后端的验证结果，并路由跳转到main.vue中
      let url = "/studyadmin/role/login"
      this.$axios.post(url, _this.loginForm).then(function (serverData) {
        if (serverData.data.code === 0 ) {
          if(serverData.data.data.roleCode==="1"){
            _this.$router.replace("/student");
          }else {
            _this.$router.replace("/teacher");
          }
//此处暂时存入未加密的信息，后期完善需要加入JWT加密串
          window.sessionStorage.setItem("loginUserInfo",JSON.stringify(serverData.data.data));
          _this.loginStateStore.loginJwt=serverData.data.data;
          _this.loginStateStore.loginUserName=_this.loginForm.stuNum;

          window.sessionStorage.setItem("userNum",_this.loginForm.stuNum);
          // console.log("98t9er8t9re",_this.loginStateStore.loginUserName)


        } else {
          //此处可以跳转到注册界面
          ElNotification({
            title: 'Warning',
            message: serverData.data.msg,
            type: 'warning',
          });
        }
      })
          .catch(function (error) {
          })
    },
    reg(){
      this.$router.push("/register")
    },
    //找回密码
    forgotPwd(){
    this.dialogPWD=true
    },
    sendEmailCode() {
      let _this = this;
      _this.$refs.registerForm.validateField('stuEmail', result => {
        console.log(this.registerForm.stuEmail)
        if (result) {
          // 按钮倒计时
          this.disabled = true;
          this.msg = this.count-- + 's后重新获取';
          this.timer = setInterval(() => {
            this.msg = this.count-- + 's后重新获取';
            if (this.count < 0) {
              this.msg = '点击获取验证码';
              this.count = 60;
              this.disabled = false;
            }
          }, 1000);


          let url1 = "/springboot_my_wms/common/request"

          _this.$axios.post(url1,{"stuEmail":_this.registerForm.stuEmail} ).then(_ => {
            // console.log("后端传过来的验证码：", _.data.data)
            // console.log("此时表中数据",this.registerForm)
            //发送验证后的邮箱
            if(_.data.code===0){
              let url2 = "/springboot_my_wms/common/email"
              _this.registerForm.code = _.data.data
              _this.$axios.post(url2,this.registerForm).then(_ => {
                if (_.data.code===0) {
                  // 通知邮箱发送
                  _this.$notify({
                    title: '邮箱验证码已发送',
                    message: '验证码有效时长5分钟, 失效请重新发送',
                    type: 'success',
                    duration: 10 * 1000
                  })
                }else {
                  ElNotification({
                    title: 'Warning',
                    message: _.data.msg,
                    type: 'warning',
                  });
                }
              })
            }else {
              ElNotification({
                title: 'Warning',
                message: _.data.msg,
                type: 'warning',
              });
            }

          })
        }
      });
    },
    submitForm() {
      this.$refs.registerForm.validate((valid) => {

        console.log("表单数据信息：", this.registerForm)
        if (valid) {
          this.loading = true
          let _this = this;
          // let url = "/studyadmin/student/register"
          // _this.$axios.post(url, _this.registerForm).then(function (serverData) {
          //   console.log("服务端返回的数据为:", serverData.data);
          //   if (serverData.data.code == 0) {
          //     ElNotification({
          //       title: 'Success',
          //       message: '注册成功',
          //       type: 'success',
          //     });
          //   } else {
          //     ElNotification({
          //       title: 'Warning',
          //       message: serverData.data.msg,
          //       type: 'warning',
          //     });
          //   }
          // }).finally(_ => {
          //   this.loading = false
          // })
        }
      });
    },

  }
}

</script>

<style>
.loginBody {
  height: 600px;

  display: flex;
  justify-content: center;
  align-items: center;
  /*background-color: lightblue;*/
  background-image: url("src/assets/background.jpeg");

  background-size: 100% 100%;

}
.forgotPWD-form input::-webkit-outer-spin-button,
.forgotPWD-form input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
.forgotPWD-form input[type='number'] {
  -moz-appearance: textfield;
}
.b span {
  font-size: 12px;
  cursor: pointer;
  /*display: inline-block;*/

  display: flex;
  justify-content: center;
  align-items: center;


}

.loginDiv {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -200px;
  margin-left: -250px;
  width: 450px;
  height: 330px;
  background: #fff;


  box-sizing: border-box;

  opacity: 0.8;
  padding: 20px 50px;
  border-radius: 5%;

}
.login-title {
  margin: 20px 0;
  text-align: center;
}
.login-content {
  width: 400px;
  height: 250px;
  position: absolute;
  top: 25px;
  left: 25px;
}
</style>
